<?php
session_start();
// 权限验证（仅超级管理员可访问）
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

$users = [];
$error = '';
$success = '';

// 处理状态更新
if (isset($_GET['action']) && $_GET['action'] === 'status' && isset($_GET['id']) && isset($_GET['status'])) {
    $id = (int)$_GET['id'];
    $status = (int)$_GET['status'];
    
    // 禁止禁用自己
    if ($id == $_SESSION['user_id']) {
        $error = "不能禁用当前登录账号";
    } else {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
            $stmt = $pdo->prepare("UPDATE user SET status = :status WHERE id = :id");
            $stmt->execute([':status' => $status, ':id' => $id]);
            header('Location: user.php?success=用户状态已更新');
            exit;
        } catch (PDOException $e) {
            $error = "状态更新失败：" . $e->getMessage();
        }
    }
}

// 处理删除
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    // 禁止删除自己
    if ($id == $_SESSION['user_id']) {
        $error = "不能删除当前登录账号";
    } else {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
            $stmt = $pdo->prepare("DELETE FROM user WHERE id = :id");
            $stmt->execute([':id' => $id]);
            header('Location: user.php?success=用户已删除');
            exit;
        } catch (PDOException $e) {
            $error = "删除失败：" . $e->getMessage();
        }
    }
}

// 加载用户列表
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $stmt = $pdo->query("SELECT id, username, email, is_admin, status, register_time 
                        FROM user 
                        ORDER BY register_time DESC");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = "用户加载失败：" . $e->getMessage();
}

// 接收提示信息
if (isset($_GET['success'])) $success = $_GET['success'];
if (isset($_GET['error'])) $error = $_GET['error'];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - IT知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/common.css">
</head>
<body>
    <div class="admin-container">
        <!-- 统一侧边栏 -->
        <aside class="admin-sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <i class="fas fa-cogs"></i>
                    <span>知识库管理</span>
                </div>
            </div>
            <ul class="nav-list">
                <li class="nav-item">
                    <a href="index.php" class="nav-link">
                        <i class="fas fa-home"></i>
                        <span>管理首页</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="article.php" class="nav-link">
                        <i class="fas fa-file-alt"></i>
                        <span>文章管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="category.php" class="nav-link">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="version.php" class="nav-link">
                        <i class="fas fa-sync-alt"></i>
                        <span>版本管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="user.php" class="nav-link active">
                        <i class="fas fa-users"></i>
                        <span>用户管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="logout.php" class="nav-link">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>退出登录</span>
                    </a>
                </li>
            </ul>
        </aside>

        <!-- 内容区 -->
        <main class="admin-content">
            <div class="content-wrapper">
                <div class="page-header">
                    <h1 class="page-title">用户管理</h1>
                    <a href="user_add.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i>新增用户
                    </a>
                </div>

                <!-- 提示信息 -->
                <?php if ($success): ?>
                    <div class="message message-success">
                        <i class="fas fa-check-circle"></i>
                        <span><?php echo $success; ?></span>
                    </div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="message message-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo $error; ?></span>
                    </div>
                <?php endif; ?>

                <!-- 用户列表 -->
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>邮箱</th>
                                <th>角色</th>
                                <th>状态</th>
                                <th>注册时间</th>
                                <th style="width: 200px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($users)): ?>
                                <tr>
                                    <td colspan="7" style="text-align: center; padding: 30px;">暂无用户记录</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td><?php echo $user['id']; ?></td>
                                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                                        <td><?php echo htmlspecialchars($user['email'] ?? '未设置'); ?></td>
                                        <td>
                                            <?php echo $user['is_admin'] == 1 ? 
                                                '<span style="color: #165DFF;">管理员</span>' : 
                                                '<span style="color: #475569;">普通用户</span>'; ?>
                                        </td>
                                        <td>
                                            <?php if ($user['status'] == 1): ?>
                                                <span style="color: #36D399;">正常</span>
                                                <a href="?action=status&id=<?php echo $user['id']; ?>&status=0" 
                                                   class="btn btn-danger btn-sm" 
                                                   style="margin-left: 8px; padding: 2px 6px;"
                                                   onclick="return confirm('确定要禁用该用户吗？')">
                                                    禁用
                                                </a>
                                            <?php else: ?>
                                                <span style="color: #F87272;">禁用</span>
                                                <a href="?action=status&id=<?php echo $user['id']; ?>&status=1" 
                                                   class="btn btn-primary btn-sm" 
                                                   style="margin-left: 8px; padding: 2px 6px;"
                                                   onclick="return confirm('确定要启用该用户吗？')">
                                                    启用
                                                </a>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo $user['register_time']; ?></td>
                                        <td class="action-buttons">
                                            <a href="user_edit.php?id=<?php echo $user['id']; ?>" class="btn btn-outline btn-sm">
                                                <i class="fas fa-edit"></i>编辑
                                            </a>
                                            <a href="javascript:confirmDelete(<?php echo $user['id']; ?>)" 
                                               class="btn btn-danger btn-sm"
                                               <?php echo $user['id'] == $_SESSION['user_id'] ? 'disabled style="opacity: 0.5; cursor: not-allowed;"' : ''; ?>>
                                                <i class="fas fa-trash"></i>删除
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>

    <script>
        function confirmDelete(id) {
            if (confirm('确定要删除该用户吗？删除后不可恢复。')) {
                window.location.href = "user.php?action=delete&id=" + id;
            }
        }
    </script>
</body>
</html>